package cn.com.company.main.client.control;

import com.extjs.gxt.ui.client.data.BasePagingLoader;
import com.extjs.gxt.ui.client.data.JsonPagingLoadResultReader;
import com.extjs.gxt.ui.client.data.LoadEvent;
import com.extjs.gxt.ui.client.data.Loader;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.data.ModelType;
import com.extjs.gxt.ui.client.data.PagingLoadResult;
import com.extjs.gxt.ui.client.data.PagingLoader;
import com.extjs.gxt.ui.client.data.ScriptTagProxy;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.VerticalPanel;
import com.extjs.gxt.ui.client.widget.form.ComboBox;
import com.google.gwt.user.client.Element;

public class AdvancedComboBox extends LayoutContainer {
	ComboBox<ModelData> combo;
	@Override
	protected void onRender(Element parent, int index) {
		
		super.onRender(parent, index);
		//String url = "http://www.extjs.com/forum/topics-remote.php";
		String url = "dataAccessServlet?op=auto";
		ScriptTagProxy<PagingLoadResult<ModelData>> proxy = new ScriptTagProxy<PagingLoadResult<ModelData>>(
				url);

		ModelType type = new ModelType();
		type.setRoot("topics");
		type.setTotalName("totalCount");
		type.addField("fnumber", "fnumber");

		JsonPagingLoadResultReader<PagingLoadResult<ModelData>> reader = new JsonPagingLoadResultReader<PagingLoadResult<ModelData>>(
				type);

		PagingLoader<PagingLoadResult<ModelData>> loader = new BasePagingLoader<PagingLoadResult<ModelData>>(
				proxy, reader);

		loader.addListener(Loader.BeforeLoad, new Listener<LoadEvent>() {
			public void handleEvent(LoadEvent be) {
				be.<ModelData> getConfig().set("start",
						be.<ModelData> getConfig().get("offset"));
			}
		});

		ListStore<ModelData> store = new ListStore<ModelData>(loader);

		combo = new ComboBox<ModelData>();
		combo.setWidth(205);
		combo.setDisplayField("fnumber");
		combo.setItemSelector("div.search-item");
		combo.setTemplate(getTemplate());
		combo.setStore(store);
		combo.setHideTrigger(true);
		combo.setPageSize(10);
		combo.setMinChars(1);

		VerticalPanel vp = new VerticalPanel();
		vp.add(combo);

		add(vp);
	}
	
	public String getInputValue(){
		String text = combo.getRawValue();
		return text;
	}

	private native String getTemplate() /*-{
		return [
				'<tpl for="."><div class="search-item">',
				'{fnumber}',
				'', '</div></tpl>' ].join("");
	}-*/;

}
